package cn.com.pansky.payment;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.pansky.util.AppUtils;
import cn.com.pansky.util.HttpClientUtil;
import cn.com.pansky.util.PayUtils;
import cn.com.pansky.util.RequestUtils;

import com.google.common.collect.Maps;
//获取请求参数
//定义接口数据集合
//定义接口参数
// 生成加密签名串
// 处理清算平台同步返回结果
// 将字符串转为XML
// 获取根节点
// 返回码
// 获取根节点下的子节点document
// document下的子节点queryorder下的子节点transType的值
// 签名验证
// 构造签名参数数组
// 生成加密签名串
//此处添加商户业务逻辑
public class RefQueryServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	public Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {
		
		//获取请求参数
		Map<String, String> reqMap = RequestUtils.getReqMap(request);
		
		//定义接口数据集合
		Map<String, String> paramMap = Maps.newHashMap();
		
		//定义接口参数
		String[] paramKeys = new String[]{ "version","charset","signMethod","transType","merId","orderTime","orderNumber","refId","qid"};

		for (String item : paramKeys) {
			paramMap.put(item, reqMap.get(item));
		}
		
		String sign = PayUtils.signDictionary(paramMap, paramKeys,reqMap.get("signKey"),reqMap.get("charset"));// 生成加密签名串
		paramMap.put("sign", sign);
		
		System.out.println("向清算平台发送退款查询请求:" + AppUtils.restMapToStr(paramMap));
		String ret = HttpClientUtil.httpPost(reqMap.get("refQurUrl"), paramMap, reqMap.get("charset"));
		System.out.println("清算平台同步响应:" + ret);
		
		// 处理清算平台同步返回结果
		readXml(ret, PayConf.SIGNKEY, reqMap.get("charset"));
	}
	
	private void readXml(String xml, String signKey, String charset) {
		Document doc = null;
		String transType = StringUtils.EMPTY;
		String merId = StringUtils.EMPTY;
		String orderNumber = StringUtils.EMPTY;
		String refId = StringUtils.EMPTY;
		String qid = StringUtils.EMPTY;
		String payAmount = StringUtils.EMPTY;
		String refundAmount = StringUtils.EMPTY;
		String state = StringUtils.EMPTY;
		String orderCurrency = StringUtils.EMPTY;
		String refConfTime = StringUtils.EMPTY;
		String sign = StringUtils.EMPTY;
		try {
			doc = DocumentHelper.parseText(StringUtils.trim(xml)); // 将字符串转为XML
			Element rootElt = doc.getRootElement(); // 获取根节点
			String respCode = rootElt.elementText("respCode");// 返回码
			if (respCode.equals("00")) {
				Iterator<?> iter = rootElt.elementIterator("list"); // 获取根节点下的子节点document
				while (iter.hasNext()) {
					Element itemEle = (Element) iter.next();
					transType = itemEle.elementTextTrim("transType"); // document下的子节点queryorder下的子节点transType的值
					merId = itemEle.elementTextTrim("merId");
					orderNumber = itemEle.elementTextTrim("orderNumber");
					refId = itemEle.elementTextTrim("refId");
					qid = itemEle.elementTextTrim("qid");
					payAmount = itemEle.elementTextTrim("payAmount");
					refundAmount = itemEle.elementTextTrim("refundAmount");
					orderCurrency = itemEle.elementTextTrim("orderCurrency");
					state = itemEle.elementTextTrim("state");
					refConfTime = itemEle.elementTextTrim("refConfTime");
					sign = itemEle.elementTextTrim("sign");
					
					// 签名验证
					Map<String, String> paramMap = new HashMap<String, String>();
					paramMap.put("transType", transType);
					paramMap.put("merId", merId);
					paramMap.put("orderNumber", orderNumber);
					paramMap.put("refId", refId);
					paramMap.put("qid", qid);
					paramMap.put("payAmount", payAmount);
					paramMap.put("refundAmount", refundAmount);
					paramMap.put("orderCurrency", orderCurrency);
					paramMap.put("state", state);
					paramMap.put("refConfTime", refConfTime);
					String[] paramKeys = new String[] { "transType", "merId", "orderNumber", "refId", "qid", "payAmount","refundAmount","orderCurrency", "state", "refConfTime"};// 构造签名参数数组
					String calsign = PayUtils.signDictionary(paramMap, paramKeys, signKey, charset);// 生成加密签名串
					if (calsign.toUpperCase().equals(sign.toUpperCase())) {
						System.out.println("签名验证成功");
						
						//此处添加商户业务逻辑
						
						
					} else {
						System.out.println("签名验证失败");
					}
				}
			} else {
				System.out.println("退款查询失败");
				String respMsg = rootElt.elementText("respMsg");
				System.out.println(AppUtils.URLDecode(respMsg, charset));
			}
		} catch (DocumentException e) {
			System.out.println("返回的XML文件解析错误1!" + e.getMessage());
		} catch (Exception e) {
			System.out.println("返回的XML文件解析错误2!" + e.getMessage());
		}
	}
}
